<?php

namespace App\Admin\Controllers;

use App\Miya\Models\Msg;
use App\Miya\Models\MsgForm;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Encore\Admin\Widgets\Table;

class MsgController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '询盘信息';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Msg());
        $grid->model()->with(['msg_form']);

        $grid->column('id', '序号');
        $grid->column('msg_form_id', '表单')->display(function () {
            return $this->msg_form->name;
        })->label();
        $grid->column('data', '询盘信息')->display(function () {
            $data = [];
            foreach ($this->data as $key => $value) {
                $data[] = sprintf('%s:%s', $key, $value);
            }

            return nl2br(implode(PHP_EOL, $data));
        });
        $grid->column('created_at', '创建时间')->display(function () {
            return $this->created_at->format('Y-m-d H:i:s');
        });
        $grid->column('is_read', '是否查阅')->radio(Msg::$readStates);

        $grid->disableCreateButton();
        $grid->disableActions();

        $grid->filter(function (Grid\Filter $filter) {
            $filter->disableIdFilter();
            $filter->equal('msg_form_id', '表单')->select(MsgForm::pluck('name', 'id'));
            $filter->equal('is_read', '是否查阅')->select(Msg::$readStates);
        });
        return $grid;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Msg());
        $form->radio('is_read', '查阅状态')->default(2)->options(Msg::$readStates);
        return $form;
    }
}
